package cn.jy.boot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        自定义认证失败信息
        Map<String,Object> info = new HashMap<>();
        info.put("msg","认证失败");
        info.put("code","500");
        info.put("exception",exception.getMessage());
//        将认证失败信息转化为json
        String json = new ObjectMapper().writeValueAsString(info);
//        将json响应
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().print(json);
    }
}
